//
//  TripManager.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/9/28.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class TripManager: NSObject {
    
    /// 单例对象
    static let share = TripManager()
    private let tripListKey = ("tripListKey" + kDomain).kf.md5
    private let lastTripIDKey = ("_lasttripid" + kDomain).kf.md5
    private let lastTripKey = ("_lasttrip" + kDomain).kf.md5
    
    private var _lasttripid: String? {
        
        set {
            
            UserDefaults.standard.set(newValue, forKey: lastTripIDKey)
            UserDefaults.standard.synchronize()
        }
        get {
            
            return UserDefaults.standard.string(forKey: lastTripIDKey)
        }
    }
    
    private var _lasttrip: Trip? {
        
        set {
            
            let ecoder = JSONEncoder()
            
            if let trip = newValue,let data = try? ecoder.encode(trip) {
                
                UserDefaults.standard.set(data, forKey: lastTripKey)
                UserDefaults.standard.synchronize()
            } else {
                
                UserDefaults.standard.removeObject(forKey: lastTripKey)
            }
        }
        get {
            
            if let data = UserDefaults.standard.data(forKey: lastTripKey) {
                
                let decoder = JSONDecoder()
                
                decoder.dateDecodingStrategy = .secondsSince1970
                
                return try? decoder.decode(Trip.self, from: data)
            }
            return nil
        }
    }
    
    private var _trips:[Trip]? {
        
        set {
            
            let ecoder = JSONEncoder()
            
            if let _trips = newValue,let data = try? ecoder.encode(_trips) {
                
                UserDefaults.standard.set(data, forKey: tripListKey)
                UserDefaults.standard.synchronize()
            } else {
                
                UserDefaults.standard.removeObject(forKey: tripListKey)
            }
        }
        get {
            
            if let data = UserDefaults.standard.data(forKey: tripListKey) {
                
                let decoder = JSONDecoder()
                
                decoder.dateDecodingStrategy = .secondsSince1970
                
                return try? decoder.decode([Trip].self, from: data)
            }
            return nil
        }
    }
    
    
    private override init() {
        super.init()
        
        self.lasttripid = _lasttripid
        self.lasttrip = _lasttrip
        self.trips = _trips
    }
    
    
    /// 当前行程ID
    var lasttripid:String? {
        
        didSet {
            
            _lasttripid = lasttripid
        }
    }
    
    /// 当前行程
    var lasttrip:Trip? {
        
        didSet {
            
            _lasttrip = lasttrip
           
        }
    }
    
    /// 行程列表
    var trips:[Trip]? {
        
        didSet {
            
            _trips = trips
        }
    }
    
    
    /// 最优行程ID
    var besttripid:String? {
        
//        如果上次查看的行程已经结束 ，下次打开进入到行程列表页面
        
        if isTripOver(_lasttrip) {
            
            return nil
        }
        
        if let lastid = lasttripid {
            
            if hasBindTrip(lastid) != nil  {
                
                return lastid
            }
        }
        
        if let trip = trips?.first {
            
            if isTripOver(trip) {
                
                return nil
            }
            
            return trip.orderId
        }

        return nil
    }
    
    #warning("--------- 此处不确定，先注释掉这个逻辑")
    /// 判断行程是否结束
    ///
    /// - Parameter trip: 行程
    /// - Returns: 是否结束
    private func isTripOver(_ trip:Trip?) -> Bool {
        
//        if let trip = trip,let datestr = trip.returnDate, let date = Date.date(datestr, "yyyy-MM-dd")  {
//            
//            if date.compare(Date()) == .orderedAscending {
//                
//                return true
//            }
//        }
        
        return false
    }
    
    
    
    
    
    
    /// 刷新行程列表
    ///
    /// - Parameter complete: --
    func reloadTripData() {
        
        NetAPI.mytrips.request([Trip].self) {
            
            response, errmsg in
            
            if let array = response as? [Trip] {
                
                self.trips = array
            }
            
            NotificationCenter.default.post(name: NSNotification.Name("reloadTripFinished"), object: nil, userInfo:  ["errmsg":errmsg ?? 0])
        }
    }
    
    
    /// 绑定行程
    ///
    /// - Parameters:
    ///   - tripid: 行程ID
    ///   - complete: --
    func bindTrip(tripid:String,complete:@escaping((_ errmsg:String?) -> Void)) {
        
        NetAPI.bindtrips(tripid: tripid).request {
            
            _, errmsg in
            
            complete(errmsg)
        }
    }
    
    
    /// 行程是否已经绑定过
    ///
    /// - Parameter _tripid: 行程ID
    /// - Returns: --
    func hasBindTrip(_ tripid:String) -> Trip? {
        
//         return trips?.contains(where: { trip -> Bool in
//
//            return trip.orderId == _tripid
//        }) ?? false
        
        
        var mtrip:Trip? = nil
        
        trips?.forEach({ trip in
            
            if trip.orderId == tripid {
                
                mtrip = trip
            }
        })
        
        return mtrip
    }
    
}

